package com.gupt.reggie.service.impl;/*
@author name
@data 2023/4/29-15:50
*/


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gupt.reggie.entity.ShoppingCart;
import com.gupt.reggie.mapper.ShoppingCartMapper;
import com.gupt.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@Service
@Slf4j
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {
    @Override
    public ShoppingCart add(HttpSession session, ShoppingCart shoppingCart) {
        log.info("添加购物车数据：{}",shoppingCart);

        //设置用户id，查询当前为哪个用户登录
        Long userId = (Long)session.getAttribute("user");
//        Long userId =(Long) request.getSession().getAttribute("user");   一样效果
        shoppingCart.setUserId(userId);

        //查询当前菜品或套餐是否在购物车中
        Long dishId = shoppingCart.getDishId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(userId != null,ShoppingCart::getUserId,userId);


        if(dishId != null){
            //添加到购物车的是菜品
            queryWrapper.eq(ShoppingCart::getDishId,dishId);
        }else{
            //添加到购物车的是套餐
            queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }
        //select * from shopping_cart where user_id = ? and dih_id / setmeal_id = ?
        ShoppingCart cartServiceOne = this.getOne(queryWrapper);


        if(cartServiceOne != null){
            //如果已存在，则当前数量加一
            //修改
            Integer number = cartServiceOne.getNumber();
            cartServiceOne.setNumber(number + 1);
            this.updateById(cartServiceOne);
        }else{
            //如果不存在，则默认数量为一
            //保存
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            this.save(shoppingCart);
            //方便返回
            cartServiceOne = shoppingCart;
        }
        return cartServiceOne;
    }
}
